import passportService from '../config'
import type { MockMethod } from 'vite-plugin-mock'
import { setToken } from '../../utils/auth'
console.log('USE_MOCK:', process.env.USE_MOCK)


// 保留mock数据作为备选方案
export const mockLogin = [
  {
    url: '/user/login',
    method: 'post',
    response: (req: { body: { username: string; password: string } }) => {
      const { username, password } = req.body
      
      const mockUsers = [
        { username: 'admin', password: '123456', token: 'admin-token', avatar: 'https://example.com/avatar1.jpg', role: 'admin', nickname: '管理员' },
        { username: 'user', password: '123456', token: 'user-token', avatar: 'https://example.com/avatar2.jpg', role: 'user', nickname: '普通用户' },
        { username: 'editor', password: '654321', token: 'editor-token', avatar: 'https://example.com/avatar3.jpg', role: 'editor', nickname: '编辑' },
        { username: 'guest', password: '111111', token: 'guest-token', avatar: 'https://example.com/avatar4.jpg', role: 'guest', nickname: '访客' }
      ]
      
      const user = mockUsers.find(item => item.username === username && item.password === password)
      
      if (!user) {
        return {
          code: 200,
          success: false,
          message: '用户名或密码错误',
          data: null
        }
      }
      
      return {
        code: 200,
        success: true,
        message: '登录成功',
        data: {
          token: user.token,
          avatar: user.avatar,
          role: user.role,
          nickname: user.nickname
        }
      }
    }
  }
] as MockMethod[]

export const login = (data: { username: string; password: string }) => {
    if (process.env.USE_MOCK) {
      const result = mockLogin[0].response({ body: data })
      console.log('mockLogin[0].response({ body: data })', result)
      if (result.success) {
        setToken(result.data.token)
        localStorage.setItem('user-base-info', JSON.stringify(result.data))
      }
      return result
    }
    return passportService({
      url: '/user/login',
      method: 'post',
      data
    }).then(res => {
      if (res.success) {
        setToken(res.data.token)
        localStorage.setItem('user-base-info', JSON.stringify(res.data))
      }
      return res
    })
  }
  